	<template>
  <view>
    <u-sticky class="u-sticky">
      <u-tabs
        :list="tabList"
        :is-scroll="false"
        :current="current"
        @change="change"
        active-color="#3E97B0"
        font-size="32"
        inactive-color="#666666"
        bg-color="#FAFAFA"
      ></u-tabs>
      <view class="padding-sm flex bg-blue light ">
        <view style="width: 100%"
            ><u-search
              placeholder="项目编号/名称/状态等"
              v-model="keyword"
              bg-color="#fff"
              :show-action="false"
              disabled="true"
              @click="search"
              searchIconSize="26"
              :inputStyle="inputStyle"
            ></u-search
          ></view>
          <u-icon
            @click="search"
            :name="filterIcon"
            size="60"
            class="margin-sm-left flex-sub margin-sm-right"
          ></u-icon>
        </view>
    </u-sticky>

    <!--  -->
    <scroll-view
      scroll-y="true"
      :style="{ height: computedScrollViewHeight }"
      @scrolltolower="loadMore"
      :refresher-enabled="true"
      :scrolltolower-enabled="true"
      :refresher-triggered="triggered"
      @refresherrefresh="refresherrefresh"
      @scrolltoupper="refresherrefresh"
      class="scroll-view-class"
    >
      <view
        class="scroll-content"
        ref="scrollContent"
        style="
          display: flex;
          flex-direction: column;
          justify-content: space-between;
        "
        :style="{ height: computedScrollViewHeight  }"
      >
        <view
          class="radius padding align-center padding-top-xl position margin-bottom-lg margin-right-sm margin-left-sm bg-white"
          v-for="(item, index) in list"
          :key="item.projectno"
          
        >
		<!-- @click="goIndex(JSON.stringify(item))" -->
        <view @click="goIndex(JSON.stringify(item))" class="flex-column justify-between align-center margin-bottom-sm">
              <view class="text-lg xmlb-item-1 ">{{ item.projectname }}</view>
              <view><dictLabel
                :value="item.projStatus ? item.projStatus : '0'"
                dict-type="zf_proj_status"
                :dict-list="dictList"
              ></dictLabel></view>
          </view>
          <view @click="goIndex(JSON.stringify(item))" class="flex-column justify-between">
              <view class="xmlb-item flex ">{{ item.projectno }}</view>
              <view class="flex flex-end ">
                <dictLabel
                :value="item.bdelay ? item.bdelay : '0'"
                dict-type="zf_proj_layDate_flag"
                :dict-list="dictLayDateList"
              ></dictLabel>
              <dictLabel
                v-if="item.boverdue!=0"
                :value="item.boverdue ? item.boverdue : '0'"
                dict-type="zf_proj_overDate_flag"
                :dict-list="dictOverDateList"
              ></dictLabel>
              </view>
            </view>
          <view class="flex-column justify-between margin-top">
			  <view
			  style="color: #3E97B0;"
			    class="starIcon"
			    @click="goIndex(JSON.stringify(item))"
			  >
			    查看详情
			  </view>
			  
			  	
			 
			  <view class="flex-column justify-between">
				
			  
            <view
              class="starIcon"
              @click.stop="dkChange(item)"
              v-if="item.projStatus == '2' && item.bcheckIn == 0 && dkflag"
            >
              打卡
            </view>
            <view
              class="starIcon text-blue"
              v-else-if="item.bcheckIn != 0"
            >
            
              已打卡
            </view>
            <view
              class="starIcon text-gray"
              v-else
            >
            
              不可打卡
            </view>
            <view
              class="starIcon"
              @click.stop="starChange(item)"
              >
              <u-icon
                name="star-fill"
                :color="item.bcollection != '1' ? '#aaaaaa' : '#F3B421'"
                size="40"
              ></u-icon>
            </view>
			</view>
          </view>
        </view>
        <view v-if="list.length" class="loadmore" style="justify-self: flex-end">
          <u-loadmore :status="loadStatus"></u-loadmore>
        </view>
      <u-empty v-if="!list.length" style="height: 100%;"></u-empty>
      </view>


    </scroll-view>
    <!-- 组件 dialog -->
    <customDialog
      :modalName="modalName"
      @getModalName="getModalName"
      :dictList="dictList"
    ></customDialog>
    <view style="height: 108rpx"></view>
    <custom-tab-bar ref="customtab1" :current-index="currentIndex" @changeTab="handleTabChange" v-if="customTabBar"/>
  </view>
</template>
<script>
import customDialog from "@/pages/zfgs/index/componetns/dialog.vue";
import dictLabel from "@/pages/zfgs/index/componetns/dictLabel.vue";
import customTabBar from '@/pages/zfgs/index/componetns/customTabBar.vue';
import {hasPermission} from '@/common/fire.js'
export default {
  components: { customDialog, dictLabel,customTabBar },
  data() {
    return {
      inputStyle:{
        fontSize:'34rpx'
      },
      triggered: false,
      modalName: null,
      tabList: [
        {
          name: "全部",
        },
        {
          name: "我的收藏",
        },
        {
          name: "施工中",
        },
        {
          name: "延期中",
        },
      ],
      current: 2,
      filterIcon: "/static/image/zfgs/24gl-funnel.svg",
      keyword: "",
      query: {
        pageNo: 1,
        pageSize: 5,
        // orderBy: "a.create_date desc",
        'pmZone.pmContractor.name': '',
        'pmZone.leaderUser.userName': '',
      },
      loadStatus: "loadmore",
      list: [],
      dictList: [],
      scrollViewHeight: 0,
      headerHeight: 0,
      currentIndex:2,
      listLength:0,
      dictLayDateList:[],
      dictOverDateList:[],
      customTabBar:true,
      dkflag: hasPermission('btn:daka'),
      collectflag:hasPermission('btn:collect'),
      collectcancleflag:hasPermission('btn:quxiaoshoucang'),
    };
  },
  onShow() {
    // this.query.projStatus = 2;
    this.loadData();
    this.$refs.customtab1.getcountData()
    this.$refs.customtab1.getMsgCount()
    console.log("onShow",this.query);
    uni.$once('someEvent',(query)=>{
      this.getValue(query)
    })
    // if(this.customTabBar){
    //   console.log("onShow");
    //   this.customTabBar = false;
    //   setTimeout(()=>{
    //     console.log("onLoad",this.customTabBar);
    //     this.customTabBar = true;
    //   },100)
    // }else{
    //   this.customTabBar = true;
    // }
  },
  onLoad() {
    this.loadData();
    this.getDictList();   
    uni.$once('someEvent',(query)=>{
      this.getValue(query)
    })
  },
  mounted() {
    setTimeout(()=>{
      this.calculateScrollViewHeight();
    },500)
  },
  watch: {
    list: {
      handler(newValue) {
        // 当list数据变化时，自动获取新的长度
        // 在这里可以基于length做一些操作
        // console.log(newValue.length,'newValue.length')        
        this.listLength = newValue.length
        this.calculateScrollViewHeight();
        
      },
      immediate: true, // 添加此选项可让监听器在初始值上立即触发
      deep: true, // 如果list内部对象也可能会变化，需要这个选项
    },
    // 监听listLength的变化

  },
  computed: {
    computedScrollViewHeight() {
      return this.scrollViewHeight === 'auto' ? 'auto' : `${this.scrollViewHeight}px`;
    },
  },

  methods: {
    getValue(query){
      console.log('query',query)
      this.query = query;
      // this.query['pmZone.pmContractor.name'] = ''
      // this.query['pmZone.leaderUser.userName'] = ''
      if(this.query.pmZonePmContractorName){
        this.query['pmZone.pmContractor.name'] = this.query.pmZonePmContractorName
        delete this.query.pmZonePmContractorName
        }
        if(this.query.pmZoneLeaderUserUserName){
          this.query['pmZone.leaderUser.userName'] = this.query.pmZoneLeaderUserUserName
          delete this.query.pmZoneLeaderUserUserName
        }
      if(this.query.projStatus == 0){
        this.current = 0
      }else if(this.query.projStatus == 1 || this.query.projStatus == 3 || this.query.projStatus == 4|| this.query.projStatus == 5 || this.query.projStatus == 6 || this.query.projStatus == 7 ){
        this.current = 4
      }
    },
    handleTabChange(pagePath) {
      // 切换页面逻辑，可使用uni.navigateTo等API
      console.log('pagePath',pagePath)
      uni.reLaunch({ url: pagePath });
    },
    async calculateScrollViewHeight() {
      const query = uni.createSelectorQuery().in(this);

      // 计算u-sticky头部高度
      query
        .select(".u-sticky")
        .boundingClientRect((rect) => {
          this.headerHeight = rect.height;
        })
        .exec();

      // 计算tabbar高度，假设tabbar是一个固定的高，或者同样方式动态获取
      this.tabBarHeight = 70; // 假设tabbar高度为50px，实际应根据实际情况获取

      // 获取屏幕高度
      const systemInfo = uni.getSystemInfoSync();
      const screenHeight = systemInfo.windowHeight;

      // 计算scroll-view高度
      this.scrollViewHeight = screenHeight - (this.headerHeight + this.tabBarHeight);
      
      // 计算class为scroll-content的高度
      if(this.listLength<=3){
        this.scrollViewHeight = 'auto'
      }
    },

    getDictList() {
      this.$u.api.dictListData({ dictType: "zf_proj_status" }).then((res) => {
        this.dictList = res;
      });
      this.$u.api.dictListData({ dictType: "zf_proj_layDate_flag" }).then((res) => {
        this.dictLayDateList = res;
      });
      this.$u.api.dictListData({ dictType: "zf_proj_overDate_flag" }).then((res) => {
        this.dictOverDateList = res;
      });
    },

    starChange(item) {
      // item.projStatus = !item.projStatus;
      if (item.bcollection != '1') {
        this.$u.api.zfgs
          .collectSave({
            projectCode: item.projectno,
            projectName: item.projectname,
          })
          .then((res) => {
            if (res.result == "true") {
              item.bcollection = '1';
              this.$u.toast("收藏成功");
			  this.$forceUpdate()
              // this.loadData()
            } else {
              this.$u.toast(res.message);
            }
          });
      } else {
        this.$u.api.zfgs
          .collectCancel({
            projectCode: item.projectno,
          })
          .then((res) => {
            if (res.result == "true") {
              // item.bcollection = !item.bcollection;
			  item.bcollection = '0';
              this.$u.toast("取消成功");
			  this.$forceUpdate()
              // this.loadData()
            } else {
              this.$u.toast(res.message);
            }
          });
      }
    },
    change(index) {
      this.current = index;
      this.list = [];
      // this.query.pageNo = 1; // 重置页码
      this.query = {
        pageNo:1
      }
      this.calculateScrollViewHeight();
      this.loadData();
    },
    search() {
      // this.modalName = "DrawerModalR";
      // 隐藏tabbar
      uni.hideTabBar();
      // 跳转到 pages/zfgs/proj/info/pmProjectinformation/filterSearch
      uni.navigateTo({
        url: "/pages/zfgs/proj/info/pmProjectinformation/filterSearch",
      });
    },
    // hideModal() {
    //   this.modalName = null;
    //   // 显示tabbar
    //   uni.showTabBar();
    // },
    getModalName(item) {
      console.log(item, "getModalName===");
      // this.modalName = item;
      const { modalName, query } = item;
      this.modalName = modalName;
      this.query = query;
      if(this.query.projStatus == 0){
        this.current = 0
      }else if(this.query.projStatus == 1 || this.query.projStatus == 3 || this.query.projStatus == 4|| this.query.projStatus == 5 || this.query.projStatus == 6 || this.query.projStatus == 7 ){
        this.current = 4
      }
      console.log(this.query.projStatus ,'this.query.projStatus',this.current)
      this.loadData();
    },
    loadMore() {
      this.loadStatus = "loading";
      console.log(this.loadStatus,'this.loadStatus')
      setTimeout(() => {
        this.query.pageNo += 1;
        this.loadData("add");
      }, 100);
    },
    loadData(type) {
		uni.showLoading({
		  title: '加载中...',
		  mask: true, // 是否显示透明蒙层，防止触摸穿透
		});
      console.log(this.current,'this.current')
      if (this.current == 2) {
        this.query.projStatus = 2;

      } else if (this.current == 0) {
        const projectname = this.query.projectname
        const projectno = this.query.projectno
        const pmZonePmContractorName = this.query['pmZone.pmContractor.name']
        const pmZoneLeaderUserUserName = this.query['pmZone.leaderUser.userName']
        // 合并this.query
        this.query = {
          projStatus: "",
          pageNo: this.query.pageNo,
          pageSize: 5,
          projectname : projectname ? projectname : '',
          projectno : projectno ? projectno : '',
          applybodyname : this.query.applybodyname ? this.query.applybodyname : '',
		  ope : 'true',
          // 'pmZone.pmContractor.name': this.query['pmZone.pmContractor.name'] ? this.query['pmZone.pmContractor.name'] : '',
          // 'pmZone.leaderUser.userName': this.query['pmZone.leaderUser.userName'] ? this.query['pmZone.leaderUser.userName'] : '',

        };
        pmZoneLeaderUserUserName ? this.query['pmZone.leaderUser.userName'] = pmZoneLeaderUserUserName : ''
        pmZonePmContractorName ? this.query['pmZone.pmContractor.name'] = pmZonePmContractorName : ''
      } else if (this.current == 3) {
        this.query.ope = 2
        
      } else if (this.current == 1) {
        this.query.ope = 3
      }
      this.$u.api.zfgs
          .pmProjectinformationListData(this.query)
          .then((res) => {
			 
            if (res.list.length >= 0) {
              // this.xmList = res.list
              if (res.list.length < 5 || res.list.length == 0) {
                this.loadStatus = "nomore";
              }
              var data = res.list;
              //模拟收藏


              if (type == "add") {
                for (var i = 0; i < data.length; i++) {
                  this.list.push(data[i]);
                }
              } else {
                this.list = data;
              }
            }
			 uni.hideLoading();
          });

    },
    async refresherrefresh() {
      console.log('refresherrefresh')
      this.triggered = true;
      this.query.pageNo = 1;
      await this.loadData();
      const scrollTop = 0
      uni.pageScrollTo({
            scrollTop,
            duration: 0,
      });
      setTimeout(() => {
        this.triggered = false;
      }, 500);
      // this.triggered = false;
    },
    reset() {
      this.query = {
        pageNo: 1,
        pageSize: 5,
      };
      this.loadData();
    },
    goIndex(item) {
      uni.showLoading({
        title: '加载中...',
        mask: true, // 是否显示透明蒙层，防止触摸穿透，默认：false
      });
      uni.navigateTo({
        url: "/pages/zfgs/index/index/index?item=" + item,
        complete() {
          // 在页面跳转完成后隐藏加载提示
          uni.hideLoading();
        },
      });
    },
    dkChange(item) {
      this.$u.api.zfgs
        .journalPmJournalSave({
          projectno: item.projectno,
          // 当前日期
          ddate: this.$u.timeFormat(new Date(), "yyyy-mm-dd"),
        })
        .then((res) => {
          if (res.result == "true") {
            // this.loadData()
            this.$u.toast(res.message);
			item.bcheckIn = '1'
			this.$forceUpdate()
          } else {
            this.$u.toast(res.message);
          }
        });
    },

  },
  // 离开页面时销毁
  onUnload() {
    // 销毁定时器
    console.log('离开页面时销毁')
  },
};
</script>
<style lang="scss" scoped>
.justify-evenly{
  justify-content: flex-end;
}
.position{
  position: relative;
}
.dictLabel{
  position: absolute;
  top: 0;
  right: 0;
}
.starIcon {
  width: 138rpx;
  // width: 20%;
  // padding: 0 10px;
  min-width: 0;
  height: 80rpx;
  border-radius: 15rpx;
  border: 1rpx solid #d8d8d8;
  display: flex;
  justify-content: space-around;
  align-items: center;
  margin-right: 20rpx; // 10px 是示例间隔大小，按需调整
}

// 当只有一个元素时，去除最后一个元素的右边距
.starIcon:last-child {
  margin-right: 0;
}
.xmlb-item-1 {
  font-size: 34rpx;
  color: #3d3d3d;
}
.xmlb-item-2 {
  padding: 6rpx 16rpx;
  border-radius: 180rpx;
  font-size: 24rpx;
  margin-left: 10rpx;
}
.xmlb-item {
  line-height: 32rpx;
  color: #999999;
  font-size: 26rpx;
  margin-top: 8rpx;
}
.margin {
  margin: 0rpx 16rpx 16rpx 16rpx;
}
.bg-gray {
  background-color: #fafafa;
}
.text-lg {

  width: 500rpx; /* 或者固定宽度：width: 385rpx; */
}
.flex-column {
  display: flex;
}
.bg-bg-red {
  background: #ffffff;
  .xmlb-item-1,
  .xmlb-item {
    color: #e1190b;
  }
}
::v-deep .u-empty{
  // 垂直居中
  min-height:calc(100vh - 55px)

}
</style>